<template>
  <div>
    <!-- 搜索 -->
    <Search
      v-model="queryModel.query"
      :loading="queryLoading"
      @search="
        queryModel.pagenum = 1;
        getUsersList();
      "
      @click="
        model = {};
        $refs.d.show();
      "
    >
      添加用户
    </Search>
    <!-- 表格 -->
    <MyTable
      :loading="tableLoading"
      :data="list"
      :cols="cols"
      :total="total"
      v-model="queryModel"
      @change="getUsersList"
    >
      <template v-slot:state="{ row }">
        <el-switch
          v-model="row.mg_state"
          @change="switchState(row)"
        ></el-switch>
      </template>
      <template v-slot:action="{ row }">
        <el-button
          type="primary"
          size="mini"
          @click="
            model = { ...row };
            $refs.d.show();
          "
          >编辑</el-button
        >
        <el-button type="danger" size="mini" @click="deleteUser(row)"
          >删除</el-button
        >
        <el-button
          type="warning"
          size="mini"
          @click="
            model = { ...row };
            getRoleList();
          "
          >设置角色</el-button
        >
      </template>
    </MyTable>

    <!-- 添加修改 -->
    <MyDialog :title="title + '用户'" ref="d" @confirm="confirm">
      <el-form label-width="70px" :model="model" :rules="rules" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input
            :disabled="!!model.id"
            v-model="model.username"
            :maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!model.id">
          <el-input v-model="model.password" :maxlength="15"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="model.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="model.mobile"></el-input>
        </el-form-item>
      </el-form>
    </MyDialog>
    <!-- 分配角色 -->
    <MyDialog title="分配角色" ref="ad" @confirm="changeRole">
      <p>当前的用户:{{ model.username }}</p>
      <p>当前的角色:{{ model.role_name }}</p>
      <p>
        分配新角色:
        <el-select v-model="model.rid">
          <el-option
            v-for="item in roles"
            :key="item.id"
            :lable="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
    </MyDialog>
    <MyForm v-model="model" :opts="opts"></MyForm>
  </div>
</template>

<script>
import { getUsers, changeState, addUser, updateUser, delUser } from "api/user";
import { getRoles, updateRole } from "api/rights";
import { pageMixins } from "@/mixins/baseMixins";
const opts = {
  username: {
    title: "用户名",
    required: true,
    max: 10,
    ph: "请输入用户名",
    rules: [{ min: 5 }],
  },
  password: {
    title: "密码",
    required: true,
    type: "passowrd",
    max: 15,
    ph: "请输入密码",
  },
};

export default {
  name: "users",
  mixins: [pageMixins],
  data() {
    return {
      /**
       * 添加修改模型
       */
      model: {},
      /**
       * 规则
       */
      rules: {
        username: [
          { required: true, message: "用户名不能为空" },
          { min: 3, max: 10, message: "用户名长度为3-10位" },
        ],
        password: [
          { required: true, message: "密码不能为空" },
          { min: 6, max: 15, message: "用户名长度为6-15位" },
        ],
        email: [
          { required: true, message: "邮箱不能为空" },
          { type: "email", message: "邮箱格式不正确" },
        ],
        mobile: [
          { required: true, message: "手机不能为空" },
          { pattern: /^1[3-9]\d{9}$/, message: "手机格式不正确" },
        ],
      },

      /**
       * 角色列表
       */
      roles: [],
      /**
       * 表格loading
       */
      tableLoading: false,
      /**
       * 列
       */
      cols: [
        {
          title: "#",
          type: "index",
        },
        {
          title: "姓名",
          name: "username",
        },
        {
          title: "邮箱",
          name: "email",
        },
        {
          title: "电话",
          name: "mobile",
        },
        {
          title: "角色",
          name: "role_name",
        },
        {
          title: "状态",
          slot: "state",
          width: 80,
        },
        {
          title: "操作",
          slot: "action",
          align: "center",
          width: 270,
        },
      ],
    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    /**
     * 修改角色
     */
    async changeRole() {
      const ad = this.$refs.ad;
      try {
        ad.start();
        await updateRole(this.model.id, this.model.rid);
        this.$m.success("角色修改成功");
        ad.hide();
        this.getUsersList();
      } catch (error) {}
      ad.stop();
    },
    /**
     * 获取角色列表
     */
    async getRoleList() {
      try {
        this.tableLoading = true;
        this.roles = await getRoles();
        const rid =
          this.roles.find((c) => c.roleName === this.model.role_name)?.id ??
          this.roles[0].id;
        this.$set(this.model, "rid", rid);
        this.$refs.ad.show();
      } catch (error) {}
      this.tableLoading = false;
    },
    /**
     * 删除用户
     */
    async deleteUser({ id, username }) {
      let res;
      try {
        res = await this.$myConfirm(`您确定要删除【${username}】嘛？`);
        await delUser(id);
        this.$m.success("删除成功");
        this.getUsersList();
      } catch (error) {}
      res && res();
    },
    /**
     * 提交添加修改
     */
    async confirm() {
      const d = this.$refs.d;
      try {
        await this.$refs.form.validate();
        d.start();
        await (this.model.id ? updateUser : addUser)(this.model);
        d.hide();
        this.visible = false;
        this.$m.success(this.title + "成功");
        this.getUsersList();
      } catch (error) {}
      d.stop();
    },
    /**
     * 更改状态
     */
    async switchState(id, mg_state) {
      try {
        await changeState(id, mg_state);
        this.$m.success("状态变更成功");
      } catch (error) {}
    },
    /**
     * 获取用户列表
     */
    async getUsersList() {
      try {
        this.queryLoading = true;
        const { total, users } = await getUsers(this.queryModel);
        this.total = total;
        this.list = users;
      } catch (error) {}
      this.queryLoading = false;
    },
  },
  computed: {
    title() {
      return this.model.id ? "修改" : "添加";
    },
  },
};
</script>

<style scoped lang="scss">
</style>
